﻿#include "application.h"

#include <QDebug>
#include <QDateTime>
#include <QDir>
#include <QTextCodec>

#include "sdk/QsLog/include/QsLog.h"
#include "sdk/QsLog/include/QsLogDest.h"

Application::Application(int argc, char **argv) : QApplication (argc, argv)
{
    // initialize the settings file
    //QString path = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
    QString path = qApp->applicationDirPath();
    m_settingsFileName = QString("%1/%2.ini").arg(path, qApp->applicationName());
    m_settings = new QSettings(m_settingsFileName, QSettings::IniFormat);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    m_settings->setIniCodec(QTextCodec::codecForName("UTF-8"));
#endif
    m_settings->beginGroup("System");
    m_settings->setValue("lastDateTime", QDateTime::currentDateTime().toString(QLocale::system().dateFormat()));
    m_settings->endGroup();

    // initialize the data base
    m_databaseName = QString("%1/%2.db3").arg(path, qApp->applicationName());
    m_sqlDatabase = QSqlDatabase::addDatabase("QSQLITE");
    m_sqlDatabase.setDatabaseName(m_databaseName);
    m_sqlDatabase.setHostName("localhost");
    //m_sqlDatabase.setUserName("");
    //m_sqlDatabase.setPassword("");
    if (!m_sqlDatabase.open())
    {
        qWarning() << "database.db3 open failed:" << m_sqlDatabase.lastError().text();
        Q_ASSERT_X(false, __FUNCTION__, "open database failed!");
    }

    // register meta type
    registerMetaType();

    // initialize QsLog
    initLogger(path);
}

Application::~Application()
{
    if (m_sqlDatabase.isOpen())
    {
        m_sqlDatabase.close();
    }

    // destroy QsLog
    destroyLogger();
}

void Application::registerMetaType()
{
    // 注册自定义数据类型
    qRegisterMetaType<QVector<double>>("QVector<double>");
}

void Application::initLogger(QString path)
{
    // log dir
    QDir logDir(path + "/logs/");
    if (!logDir.exists()) {
        logDir.mkpath(path + "/logs/");
    }

    using namespace QsLogging;

    // 1. init the logging mechanism
    Logger& logger = Logger::instance();
    logger.setLoggingLevel(QsLogging::DebugLevel);
    const QString sLogPath(QDir(path + "/logs/").filePath("log.txt"));

    // 2. add two destinations
    DestinationPtr fileDestination(DestinationFactory::MakeFileDestination(sLogPath, EnableLogRotation, MaxSizeBytes(1024 * 1024 * 10), MaxOldLogCount(2)));
    DestinationPtr debugDestination(DestinationFactory::MakeDebugOutputDestination());
    logger.addDestination(debugDestination);
    logger.addDestination(fileDestination);

}

void Application::destroyLogger()
{
    QsLogging::Logger::destroyInstance();
}


QSettings *Application::settings()
{
    return m_settings;
}

QSqlDatabase *Application::sqlDatabase()
{
    return &m_sqlDatabase;
}
